import add from './medal-add.js'
import del from './medal-del.js'

let datagrid = document.querySelector("._datagrid");

let searchForm = document.forms.searchForm;
let seId = searchForm.seId; 

let pagination = document.querySelector(".pagination");

let paginationFormat = function(data){
	let html = `<li class="page-item" data-page="1">
					<a class="page-link" href="javascript:void(0);" aria-label="Previous">
						<span aria-hidden="true">&laquo;</span>
					</a>
				</li>`;
				
	for(let i of data.pages){
		html+=`<li class="page-item ${i==data.current? 'active' : ''}" data-page="${i}"><a class="page-link" href="javascript:void(0);">${i}</a></li>`;
	}
	
	html+=`<li class="page-item" data-page="${data.pageMax}">
				<a class="page-link" href="javascript:void(0);" aria-label="Next">
					<span aria-hidden="true">&raquo;</span>
				</a>
			</li>`;
			
	pagination.innerHTML = html;
	for(let li of pagination.children){
		li.onclick=function(){
			loadData(li.dataset.page);
		}
		
	}
}

fetch("SportingEvents-list.let").then(r=>r.json()).then(data=>{
		data.forEach(item=>{
			seId.add(new Option(item.seName,item.seId));
		})
	});

let ms = ["","金","银","铜"];

let params = new URLSearchParams();

let loadData = function(current=1,rowMax=5) {
	params.set("current",current);
	params.set("rowMax",rowMax);
	fetch("medal-page.let?"+params.toString()).then((r) => r.json()).then((data) => {
		console.debug(data);
		paginationFormat(data);//格式化页码
		datagrid.innerHTML = "";
		data.list.forEach((item, index) => {
			let tr = document.createElement("tr");
			let year = new Date(item.medalDate).getFullYear();
			let mounth = new Date(item.medalDate).getMonth() + 1;
			let date = new Date(item.medalDate).getDate();
			let dd = year + "-" + mounth + "-" + date;
			tr.innerHTML = `
				<td>${item.seName}</td>
				<td>${item.countryName}</td>
				<td>${item.sportsmanName}</td>
				<td>${ms[item.medalNum]}</td>
				<td>${item.medalResult}</td>
				<td>${dd}</td>
				<td class="p-2">
					<div class="btn-group btn-group-sm">
						<button type="button" class="btn btn-danger _delete" title="删除">
							<i class="fa fa-remove"></i>
						</button>
					</div>
				</td>`;
			datagrid.appendChild(tr);
			tr.querySelector("._delete").onclick = function() {
				del(item);
			}
		});
	}).catch((e) => {
		console.error(e);
	});
}
loadData();

searchForm.onsubmit = function(event){
	event.stopPropagation();
	event.preventDefault();
	params = new URLSearchParams(new FormData(searchForm));
	loadData(1);
}

window.addEventListener("message", function(e) {
	console.debug(e);
	if (e.data == "loadData") {
		loadData();
	}
});
add();